﻿using System.Web.Mvc;
using AhoraSiMvc3.Models;

namespace AhoraSiMvc3.Controllers
{ 
    public class StudentController : Controller
    {
        //private ModelContext db = new ModelContext();

        private IStudentsRepo repo;
        private IUnitOfWorkFactory uowFactory;

        public StudentController(IStudentsRepo repo, IUnitOfWorkFactory uowFactory)
        {
            this.repo = repo;
            this.uowFactory = uowFactory;
        }

        //
        // GET: /Student/

        public ViewResult Index()
        {
            return View(repo.GetAll());
        }

        //
        // GET: /Student/Details/5

        public ViewResult Details(int id)
        {
            Student student = repo.Get(id);
            return View(student);
        }

        //
        // GET: /Student/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Student/Create

        [HttpPost]
        public ActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                using (IUnitOfWork uow = this.uowFactory.Current)
                {
                    this.repo.Add(student);
                    uow.Commit();
                    return RedirectToAction("Index");
                }
            }

            return View(student);
        }
        
        //
        // GET: /Student/Edit/5
 
        public ActionResult Edit(int id)
        {
            Student student = repo.Get(id);
            return View(student);
        }

        //
        // POST: /Student/Edit/5

        [HttpPost]
        public ActionResult Edit(Student student)
        {
            if (ModelState.IsValid)
            {
                using (IUnitOfWork uow = this.uowFactory.Current)
                {
                    this.repo.Update(student);
                    uow.Commit();
                    return RedirectToAction("Index");
                }
            }
            return View(student);
        }

        //
        // GET: /Student/Delete/5
 
        public ActionResult Delete(int id)
        {
            Student student = this.repo.Get(id);
            return View(student);
        }

        //
        // POST: /Student/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            using (IUnitOfWork uow = this.uowFactory.Current)
            {
                Student student = this.repo.Get(id);
                this.repo.Remove(student);
                uow.Commit();
                return RedirectToAction("Index");
            }
        }

        protected override void Dispose(bool disposing)
        {
            this.uowFactory.DisposeUnitOfWork();
        }
    }
}